/* eslint @typescript-eslint/no-unused-vars:off, consistent-return:off, no-useless-escape:off, */
import { defineConfig } from 'vite';
import viteCompression from 'vite-plugin-compression';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
import svgLoader from 'vite-svg-loader';
import pxToRem from 'postcss-pxtorem';
import vue from '@vitejs/plugin-vue';
import { viteVConsole } from 'vite-plugin-vconsole';
import * as path from 'path';
import postPresetEnv from 'postcss-preset-env';
import { webpDirectory } from './webp';

console.log(postPresetEnv, '🚀');

const { webp } = require('rollup-plugin-webp');

const { resolve } = require('path');
// const fs = require('fs');

// https://vitejs.dev/config/

const publicPaths = {
    development: '/',
    test: '/',
    pre: '/',
    production: '/',
};

export default defineConfig(({ mode, command }) => {
    const alias = [
        {
            find: '@',
            replacement: resolve('./src/'),
        },
        {
            find: '@img',
            replacement: resolve('./src/assets/images/'),
        },
        {
            find: '@api',
            replacement: resolve('./src/api/'),
        },
        {
            find: '@utils',
            replacement: resolve('./src/utils/'),
        },
        {
            find: '@pages',
            replacement: resolve('./src/pages'),
        },
        {
            find: '@plugins',
            replacement: resolve('./src/plugins'),
        },
        {
            find: '@comp',
            replacement: resolve('./src/components'),
        },
    ];
    if (mode !== 'production') {
        // 解决警告You are running the esm-bundler build of vue-i18n.
        alias.push({
            find: 'vue-i18n',
            replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
        });
    }
    return {
        base: publicPaths[mode], // 资源文件路径
        build: {
            outDir: '../dist', // 打包路径 默认为根目录下的 dist 文件夹
            emptyOutDir: true, // 清空之前的文件
            manifest: true, // 生成清单
            sourcemap: true,
            rollupOptions: {
                input: {
                    main: resolve(__dirname, 'index.html'),
                    // [other_name]: resolve(__dirname, 'other.html'),
                },
                output: {
                    // 指定聚合文件块
                    manualChunks(id) {
                        if (id.includes('node_modules')) {
                            const paths = id.toString().split('node_modules/');
                            return paths[paths.length - 1].split('/')[0].toString();
                        }
                    },
                    // 指定块的输出地址
                    chunkFileNames: (chunkInfo) => {
                        if (chunkInfo.modules) {
                            const reg = /dev_h5\/src\/(.*\/)/gi;
                            const penReg = /node_modules\/(?!\.pnpm)([\w@.\-?]*\/)/gi;
                            const path =
                                Object.keys(chunkInfo.modules).filter((p) =>
                                    p.includes('dev_h5')
                                )?.[0] || '';
                            const dirMatch = penReg.exec(path)?.[0] || reg.exec(path)?.[1];
                            return `js/${dirMatch || ''}[name].[hash].js`;
                        }
                        return `js/[name].[hash].js`;
                    },
                    // 指定资源打包路径
                    assetFileNames: ({ name = '' }): string => {
                        if (/\.(jpg|png|gif|svg|svga|webp)$/g.test(name)) {
                            return /(assets\/images\/.*)/g.exec(name)?.[0] ?? 'assets/[name].[ext]';
                        }
                        if (name.endsWith('.css')) {
                            return 'css/[name]-[hash].css';
                        }
                        if (/\.(js|vue)$/g.test(name)) {
                            const path = name
                                .substring(0, name.lastIndexOf('/'))
                                .replace('src/', '');
                            return `js/${path}[name].[hash].[ext]`;
                        }
                        return '[name].[hash].[ext]';
                    },
                },
            },
            assetsInlineLimit: 0, // 禁用base64编码
        },
        resolve: {
            alias,
        },
        productionSourceMap: false,
        parallel: require('os').cpus().length > 1,
        server: {
            // 限制访问工作区以外的文件
            fs: {
                strict: false,
            },
            // https: {
            //     cert: fs.readFileSync(resolve(__dirname, 'keys/cert.crt')),
            //     key: fs.readFileSync(resolve(__dirname, 'keys/cert.key')),
            // },
        },
        plugins: [
            vue({
                reactivityTransform: true,
            }),
            // 开启gzip压缩
            // viteCompression({
            //     verbose: true,
            //     disable: false,
            //     threshold: 10240,
            //     algorithm: 'gzip',
            //     ext: '.gz',
            // }),
            // 开启br压缩
            // viteCompression({
            //     threshold: 10240,
            //     algorithm: 'brotliCompress',
            //     ext: '.br',
            // }),
            // 自定义插件
            Components({
                resolvers: [VantResolver()],
            }),
            // SVG Loader
            svgLoader(),
            // 打包时生成对应图片文件名Webp
            webp({
                quality: 80,
                include: [...webpDirectory],
            }),
            viteVConsole({
                entry: path.resolve('src/main.ts'), // 或者可以使用这个配置: [path.resolve('src/main.ts')]
                localEnabled: true,
                enabled: mode !== 'production',
                config: {
                    maxLogNumber: 1000,
                    theme: 'light',
                },
            }),
        ],
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@import "@/assets/styles/common.scss";`,
                    javascriptEnabled: true,
                    charset: false,
                },
            },
            devSourcemap: false,
            postcss: {
                plugins: [
                    require('autoprefixer')({
                        overrideBrowserslist: [
                            '> 0.5%',
                            'last 2 versions',
                            'ie > 11',
                            'iOS >= 10',
                            'Android >= 5',
                        ],
                    }),
                    pxToRem({
                        rootValue: 75, // 默认转换75px=1rem(设计图宽度750px), 如果设计图宽度为375px, 请使用pxToRem函数
                        propList: ['*'],
                        selectorBlackList: ['van-', ':root', 'van_', '--van', /^body$/], // 忽略Vant组件元素
                    }),
                    postPresetEnv()
                ],
            },
        },
    };
});
